#include "order_module.h"
#include <iostream>

namespace TakeAwayPlatform
{
    OrderModule::OrderModule(DatabaseHandler& dbHandler) : dbHandler(dbHandler) {}

    //创建订单
    bool OrderModule::createOrder(int user_id, int merchant_id, int address_id, const std::vector<std::pair<int, int>>& cart_items, double total_amount)
    {
        std::string sql = "INSERT INTO orders (user_id, merchant_id, address_id, total_amount, status) VALUES (" +
                          std::to_string(user_id) + ", " + std::to_string(merchant_id) + ", " + std::to_string(address_id) + ", " +
                          std::to_string(total_amount) + ", 0)";
        if (!dbHandler.update(sql))
        {
            return false;
        }

        int order_id = dbHandler.getLastInsertId();

        for (const auto& item : cart_items)
        {
            sql = "INSERT INTO order_items (order_id, dish_id, quantity) VALUES (" +
                  std::to_string(order_id) + ", " + std::to_string(item.first) + ", " + std::to_string(item.second) + ")";
            if (!dbHandler.update(sql))
            {
                return false;
            }
        }

        return true;
    }

    //更新订单
    bool OrderModule::updateOrderStatus(int order_id, int status)
    {
        std::string sql = "UPDATE orders SET status = " + std::to_string(status) + " WHERE order_id = " + std::to_string(order_id);
        return dbHandler.update(sql);
    }

    bool OrderModule::getOrderDetails(int order_id, int& user_id, int& merchant_id, int& address_id, std::vector<std::pair<int, int>>& cart_items, double& total_amount, int& status)
    {
        std::string sql = "SELECT user_id, merchant_id, address_id, total_amount, status FROM orders WHERE order_id = " + std::to_string(order_id);
        Json::Value result = dbHandler.query(sql);

        if (result.size() > 0)
        {
            user_id = result[0]["user_id"].asInt();
            merchant_id = result[0]["merchant_id"].asInt();
            address_id = result[0]["address_id"].asInt();
            total_amount = result[0]["total_amount"].asDouble();
            status = result[0]["status"].asInt();

            sql = "SELECT dish_id, quantity FROM order_items WHERE order_id = " + std::to_string(order_id);
            Json::Value items_result = dbHandler.query(sql);

            for (const auto& item : items_result)
            {
                cart_items.push_back({item["dish_id"].asInt(), item["quantity"].asInt()});
            }

            return true;
        }

        return false;
    }

    //获取订单
    bool OrderModule::getOrdersByUser(int user_id, std::vector<int>& order_ids)
    {
        std::string sql = "SELECT order_id FROM orders WHERE user_id = " + std::to_string(user_id);
        Json::Value result = dbHandler.query(sql);

        for (const auto& row : result)
        {
            order_ids.push_back(row["order_id"].asInt());
        }

        return !order_ids.empty();
    }
}